/*****************************************************************************
 * datatypes.h: CPM server data type definitions
 *****************************************************************************
 * Copyright (C) 2012
 *
 * Authors: Dan Larkin <danielhlarkin@gmail.com>
 *          Yonatan Naamad <cached@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *****************************************************************************/

#ifndef CPM_DATATYPES
#define CPM_DATATYPES

#include "dict.h"
#include "heap.h"
#include "stack.h"
#include <netinet/ip.h>
#include <stdint.h>
#include <pthread.h>

struct cpm_peer;
struct cpm_allocation;
struct cpm_heap;
struct cpm_heap_node;

typedef struct cpm_torrent
{
    uint8_t id[20];
    int32_t size;
    int32_t min;
    int32_t max;
} cpm_torrent;

typedef struct cpm_torrent_node
{
    cpm_torrent data;
    int32_t current;
    int32_t average_time;
    cpm_heap_node *heap_node;
    struct cpm_peer *clients;
} cpm_torrent_node;

typedef struct cpm_client_node
{
    int connection;
    struct sockaddr addr;
    unsigned int addrlen;
    pthread_t thread;
    cpm_heap_node *heap_node;
    int32_t bw_total;
    int32_t bw_used;
    int32_t disk_total;
    int32_t disk_used;
    int16_t slots_total;
    int16_t slots_used;
    struct cpm_allocation *torrents;
} cpm_client_node;

typedef struct cpm_peer
{
    struct cpm_peer *next;
    struct cpm_peer *prev;
    int32_t timestamp;
    cpm_client_node *client;
} cpm_peer;

typedef struct cpm_allocation
{
    struct cpm_allocation *next;
    struct cpm_allocation *prev;
    cpm_torrent_node *torrent;
    int32_t min;
    int32_t max;
} cpm_allocation;

typedef struct cpm_server_data
{
    cpm_dict *torrent_dict;
    cpm_dict *client_dict;
    cpm_heap *client_heap;
    cpm_heap *torrent_heap;
    cpm_stack *temp;
    uint8_t key[16];
    int database_ip;
    int database_socket;
    int server_socket;
    int server_port;
    struct sockaddr_in server_addr;
    pthread_t maintenance_thread;
    pthread_mutex_t lock;
    int32_t bw_total;
    int32_t bw_used;
    int32_t disk_total;
    int32_t disk_used;
    int16_t slots_total;
    int16_t slots_used;
} cpm_server_data;

#endif
